#include<iostream>
#include<string>
#include<cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
#include<unistd.h>

using namespace std;
int main()
{
    //1.创建管道
    int fds[2]={0};//文件描述符
    int n = pipe(fds);//fds输出型参数
    if(n!=0)
    {
        cerr<<"pipe error"<<endl;
        return 1;
    }

    //2.创建进程：子进程写，父进程读
    pid_t id = fork();
    if(id<0)
    {
        cerr<<"fork error"<<endl;
        return 2;
    }
    else if(id==0)
    {
        //子进程
        close(fds[0]);//关闭不需要的fd
        int cnt = 0;
        while(true)
        {
            string message = "hello bit,hello ";
            message+=to_string(getpid());
            message+=",";
            message+=to_string(cnt);

            write(fds[1],message.c_str(),message.size());
            cnt++;
            sleep(1);
        }
        exit(0);
    }
    else{
        //父进程
        close(fds[1]);//关闭不需要的fd

        char buffer[1024];
        while(true)
        {
            ssize_t n = read(fds[0],buffer,1024);
            if(n>0)
            {
                buffer[n]=0;
                cout<<"child->father,meassage:"<<buffer<<endl;
            }
        }
        pid_t rid = waitpid(id,nullptr,0);
        std::cout << "father wait child success: " << rid <<endl;
    }
    
  
    return 0;
}